package com.lbs.jiepiaisi.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.AnswerQuestionBean;
import com.lbs.jiepiaisi.bean.UserEntity;
import com.lbs.jiepiaisi.bean.WorkOrderListBean;
import com.lbs.jiepiaisi.biz.PhotoUploadBiz;
import com.lbs.jiepiaisi.biz.QuestionHomeBiz;
import com.lbs.jiepiaisi.biz.WorkHomeOrderBiz;
import com.lbs.jiepiaisi.fragment.WorkOrderListFragment;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.utils.ImageFactory;
import com.lbs.jiepiaisi.utils.ImageWaterMaskUtil;
import com.lbs.jiepiaisi.utils.PhoneUtil;
import com.lbs.jiepiaisi.view.HomeListView;
import com.lbs.jiepiaisi.view.WaitingDialogControll;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WorkHomeOrderAddActivity extends BaseActivity implements AMapLocationListener {
    private WorkOrderListBean.Result.Item mWorkOrder;

    private HomeListView homeListView;

    private HomeQuestionReceiver homeQuestionReceiver ;

    private TextView textView1;
    private TextView textView2;
    private TextView textView3;
    private TextView textView4;


    private ImageView imageView1;
    private ImageView imageView2;
    private ImageView imageView3;
    private ImageView imageView4;

    private ImageView showImg1;
    private ImageView showImg2;
    private ImageView showImg3;
    private ImageView showImg4;

    private CheckBox mAgreeCK;

    private LinearLayout mLin;

    private Button mBtnSign;

    private Button mBtnOK;

    private TextView mNameTv;
    private TextView mCardTv;
    private TextView mTelTv;
    private TextView mContract;
    private TextView mAddress;

    private TextView mDate;
    private EditText mVisitNameEt;
    private EditText mTelEt;

    private ImageView mImgSign;

    private TextView mHomeViewText;

    public static File imgTempFile1 = new File(Environment.getExternalStorageDirectory(), "1" + getPhotoFileName());
    public static File imgTempFile2 = new File(Environment.getExternalStorageDirectory(), "2" + getPhotoFileName());
    public static File imgTempFile3 = new File(Environment.getExternalStorageDirectory(), "3" + getPhotoFileName());
    public static File imgTempFile4 = new File(Environment.getExternalStorageDirectory(), "4" + getPhotoFileName());

    private final int OPEN_RESULT_1 = 1;
    private final int OPEN_RESULT_2 = 2;
    private final int OPEN_RESULT_3 = 3;
    private final int OPEN_RESULT_4 = 4;
    private final int OPEN_RESULT_5 = 5;

    private PhotoUploadReceiver photoUploadReceiver;

    private WorkUploadReceiver workUploadReceiver;

    public static final String HOME_QUESTION = "com.lbs.jiepiaisi.activity.WorkHomeOrderAddActivity.HomeQuestionReceiver";
    private String[] ownDes = {"客户所住小区门口带有小区名称标识的",
    "客户家门口带有门牌号的", "客户客厅全貌的（含地板、沙发、顶灯等）", "其他认为具有意义的（例如：书房、含影视墙、含博古架的位置）"};
    private String[] comDes = {"含有公司招牌的外景（门头房的尽量取含周边的全景，写字楼的尽量取前台LOGO墙）","公司办公场所内景（包含：员工、工位、办公设备、机器设备、库存产品等）","跟客户在其办公场所内的合影","其他认为具有意义的（例如：悬挂在墙上的营业执照、许可证、荣誉证书等）"};
    private String[] curDes ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_home_order_add);
        getExtra();
        initView();
        setListener();
        initLocation();
    }

    private void getExtra(){
        mWorkOrder = (new Gson().fromJson(getIntent().getStringExtra("order"),WorkOrderListBean.Result.Item.class));

        if("1".equals(mWorkOrder.getHomeVisitsType())){
            curDes = ownDes;
            titleView.setText("家访-家庭");
        }else {
            curDes = comDes;
            titleView.setText("家访-公司");
        }
    }

    private void initView(){
        homeListView = (HomeListView)findViewById(R.id.home_question);

        homeQuestionReceiver = new HomeQuestionReceiver();
        IntentFilter intentFilter = new IntentFilter(HOME_QUESTION);
        getApplicationContext().registerReceiver(homeQuestionReceiver,intentFilter);

        new QuestionHomeBiz().questionBiz(mWorkOrder.getHomeVisitsType(),HOME_QUESTION);

        textView1 = (TextView)findViewById(R.id.tv_1);
        textView1.setText(curDes[0]);
        textView2 = (TextView)findViewById(R.id.tv_2);
        textView2.setText(curDes[1]);
        textView3 = (TextView)findViewById(R.id.tv_3);
        textView3.setText(curDes[2]);
        textView4 = (TextView)findViewById(R.id.tv_4);
        textView4.setText(curDes[3]);

        imageView1 = (ImageView) findViewById(R.id.img_1);
        imageView2 = (ImageView) findViewById(R.id.img_2);
        imageView3 = (ImageView) findViewById(R.id.img_3);
        imageView4 = (ImageView) findViewById(R.id.img_4);

        mLin =  (LinearLayout)findViewById(R.id.lin_sign);

        mBtnSign = (Button)findViewById(R.id.btn_sign);

        mAgreeCK = (CheckBox)findViewById(R.id.agree_ck);

        mBtnOK = (Button)findViewById(R.id.btn_ok);

        mHomeViewText = (TextView)findViewById(R.id.tv_home_rule);

        mHomeViewText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkHomeOrderAddActivity.this,HomeRuleActivity.class);
                startActivity(intent);
            }
        });

        mBtnSign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(WorkHomeOrderAddActivity.this, SignTextActivity.class),OPEN_RESULT_5);
            }
        });

        mAgreeCK.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mLin.setVisibility(View.VISIBLE);
                }else {
                    mLin.setVisibility(View.GONE);
                }
            }
        });
        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = Uri.fromFile(imgTempFile1);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, OPEN_RESULT_1);
                }
            }
        });
        imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = Uri.fromFile(imgTempFile2);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, OPEN_RESULT_2);
                }
            }
        });
        imageView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = Uri.fromFile(imgTempFile3);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, OPEN_RESULT_3);
                }
            }
        });
        imageView4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri imageUri = Uri.fromFile(imgTempFile4);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, OPEN_RESULT_4);
                }
            }
        });


        showImg1 = (ImageView)findViewById(R.id.show_img1);
        showImg2 = (ImageView)findViewById(R.id.show_img2);
        showImg3 = (ImageView)findViewById(R.id.show_img3);
        showImg4 = (ImageView)findViewById(R.id.show_img4);




        mNameTv = (TextView) findViewById(R.id.tv_name);
        mNameTv.setText(mWorkOrder.getSiteContact());
        mCardTv = (TextView) findViewById(R.id.tv_card);
        mCardTv.setText(mWorkOrder.getOwenerId());
        mTelTv = (TextView) findViewById(R.id.tv_tel);
        mTelTv.setText(mWorkOrder.getSiteContactTel());
        mContract = (TextView) findViewById(R.id.tv_contract);
        mContract.setText(mWorkOrder.getContractNo());
        mAddress = (TextView) findViewById(R.id.tv_address);
        mAddress.setText(mWorkOrder.getInstallSite());

        mDate = (TextView) findViewById(R.id.tv_date);
        mDate.setText(getCurTime());
        mVisitNameEt = (EditText) findViewById(R.id.et_visit_name);
        mTelEt = (EditText) findViewById(R.id.et_visit_tel);

        mImgSign = (ImageView)findViewById(R.id.img_sign);

        photoUploadReceiver = new PhotoUploadReceiver();
        IntentFilter intentFilter1 = new IntentFilter(ORDER_IMG);
        getApplicationContext().registerReceiver(photoUploadReceiver,intentFilter1);

        workUploadReceiver = new WorkUploadReceiver();
        IntentFilter intentFilter2 = new IntentFilter(FINISH_ORDER);
        getApplicationContext().registerReceiver(workUploadReceiver,intentFilter2);


        mBtnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadFile();
            }
        });
    }

    private String getCurTime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    private void setListener(){

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(homeQuestionReceiver != null){
            getApplicationContext().unregisterReceiver(homeQuestionReceiver);
        }
        if(photoUploadReceiver != null){
            getApplicationContext().unregisterReceiver(photoUploadReceiver);
        }
        if(workUploadReceiver != null){
            getApplicationContext().unregisterReceiver(workUploadReceiver);
        }
        mlocationClient.stopLocation();
    }

    class HomeQuestionReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            WaitingDialogControll.dismissWaitingDialog();
            AnswerQuestionBean answerQuestionBean = (AnswerQuestionBean)intent.getSerializableExtra(Constant.KEY_DATA);
            int status = answerQuestionBean.getStatus();

            if(status == Constant.STATUS_OK){
                homeListView.setQuestionList(answerQuestionBean.getResult());
            }else {
//                if(ToastUtil.isFastShow()){
                    Toast.makeText(WorkHomeOrderAddActivity.this, "加载异常", Toast.LENGTH_SHORT).show();
//                }
            }
        }
    }

    private Uri uri1;
    private Uri uri2;
    private Uri uri3;
    private Uri uri4;

    private Bitmap mBitmap1;
    private Bitmap mBitmap2;
    private Bitmap mBitmap3;
    private Bitmap mBitmap4;
    private Bitmap mBitmap5 = null;

    public static String path1 = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ls.png";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //设备号和SIM卡号拍照
            case OPEN_RESULT_1:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                imgTempFile1.getAbsolutePath(),
                                null, null));
                        uri1 = uri;
                        //uris[0] = deviceUri;
                        //通过uri获取图片并进行压缩
                        mBitmap1 = ImageFactory.getBitmapFormUri(this, uri1);
                        mBitmap1 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap1,getCurTime(),12, Color.WHITE,10,10);
                        mBitmap1 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap1, area,12, Color.WHITE,10,25);
                        mBitmap1 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap1, area2,12, Color.WHITE,10,40);
                        uri1 = saveBitmap(mBitmap1,"visit1");
                        showImg1.setImageBitmap(mBitmap1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

            case OPEN_RESULT_2:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                imgTempFile2.getAbsolutePath(),
                                null, null));
                        uri2 = uri;
                        //uris[0] = deviceUri;
                        //通过uri获取图片并进行压缩
                        mBitmap2 = ImageFactory.getBitmapFormUri(this, uri2);
                        mBitmap2 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap2,getCurTime() ,12, Color.WHITE,10,10);
                        mBitmap2 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap2, area,12, Color.WHITE,10,25);
                        mBitmap2 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap2, area2,12, Color.WHITE,10,40);
                        uri2 = saveBitmap(mBitmap2,"visit2");
                        showImg2.setImageBitmap(mBitmap2);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case OPEN_RESULT_3:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                imgTempFile3.getAbsolutePath(),
                                null, null));
                        uri3 = uri;
                        //uris[0] = deviceUri;
                        //通过uri获取图片并进行压缩
                        mBitmap3 = ImageFactory.getBitmapFormUri(this, uri3);
                        mBitmap3 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap3,getCurTime(),12, Color.WHITE,10,10);
                        mBitmap3 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap3, area,12, Color.WHITE,10,25);
                        mBitmap3 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap3, area2,12, Color.WHITE,10,40);
                        uri3 = saveBitmap(mBitmap3,"visit3");
                        showImg3.setImageBitmap(mBitmap3);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case OPEN_RESULT_4:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                                imgTempFile4.getAbsolutePath(),
                                null, null));
                        uri4 = uri;
                        //uris[0] = deviceUri;
                        //通过uri获取图片并进行压缩
                        mBitmap4 = ImageFactory.getBitmapFormUri(this, uri4);
                        mBitmap4 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap4,getCurTime() ,12, Color.WHITE,10,10);
                        mBitmap4 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap4, area,12, Color.WHITE,10,25);
                        mBitmap4 = ImageWaterMaskUtil.drawTextToLeftTop(this,mBitmap4, area2,12, Color.WHITE,10,40);
                        uri4 = saveBitmap(mBitmap4,"visit4");
                        showImg4.setImageBitmap(mBitmap4);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case  OPEN_RESULT_5: {
                if (resultCode == RESULT_OK) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 2;
                    mBitmap5 = BitmapFactory.decodeFile(path1, options);
                    mImgSign.setVisibility(View.VISIBLE);
                    mImgSign.setImageBitmap(mBitmap5);
                }
                break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 使用系统当前日期加以调正作为照片的名称
     */
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }
    //这里是在签名页面退出的时候  将页面切换为正常的屏幕 即竖屏
    @Override
    protected void onResume() {

        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();
    }
    //上传文件列表
    List<File> fileList = null;
    public static final String ORDER_IMG = "jav.com.lbs.jiepiaisi.activity.WorkHomeOrderAddActivity.IMG";
    private void uploadFile(){
        if("".equals(mVisitNameEt.getText().toString())){
            Toast.makeText(this,"请填入家访人员姓名",Toast.LENGTH_SHORT).show();
            return;
        }
        if("".equals(mTelEt.getText().toString()) ||  !PhoneUtil.checkCellphone(mTelEt.getText().toString())){
            Toast.makeText(this,"请填入正确家访人员联系方式",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!homeListView.isAllSel()){
            Toast.makeText(this,"请回答所有问题",Toast.LENGTH_SHORT).show();
            return;
        }

        //return;
        if(!mAgreeCK.isChecked()){
            Toast.makeText(this,"请先同意家访调查制度",Toast.LENGTH_SHORT).show();
            return;
        }
        fileList = new ArrayList<File>();
        if(uri1 == null){
            Toast.makeText(this,"请上传图片",Toast.LENGTH_SHORT).show();
            return;
        }
        File file1 = ImageFactory.getFileFromMediaUri(getApplicationContext(), uri1);
        if(uri2 == null){
            Toast.makeText(this,"请上传图片",Toast.LENGTH_SHORT).show();
            return;
        }
        File file2 = ImageFactory.getFileFromMediaUri(getApplicationContext(), uri2);
        if(uri3 == null){
            Toast.makeText(this,"请上传图片",Toast.LENGTH_SHORT).show();
            return;
        }
        File file3 = ImageFactory.getFileFromMediaUri(getApplicationContext(), uri3);
        if(uri4 == null){
            Toast.makeText(this,"请上传图片",Toast.LENGTH_SHORT).show();
            return;
        }
        File file4 = ImageFactory.getFileFromMediaUri(getApplicationContext(), uri4);
        if(mBitmap5 == null){
            Toast.makeText(this,"请检查并签字",Toast.LENGTH_SHORT).show();
            return;
        }
        File file5 = new File(path1);

        fileList.add(file1);
        fileList.add(file2);
        fileList.add(file3);
        fileList.add(file4);
        fileList.add(file5);
        WaitingDialogControll.showWaitingDialog(this);
       new PhotoUploadBiz().uploadBiz(fileList,mWorkOrder.getWoId()+"",ORDER_IMG);
    }

    public void uploadWork(){
        String json = homeListView.getAnswerJson(Constant.WORK_ORDER_HISTORY_GET,getCurTime(),mWorkOrder.getHomeVisitsType(),mTelEt.getText().toString(),mDate.getText().toString(),mWorkOrder.getWoId()+"",mVisitNameEt.getText().toString());
        Log.e("json","---"+json);
        new WorkHomeOrderBiz().finishgetOrderBiz(json,FINISH_ORDER);
    }
    public static final String FINISH_ORDER ="FINISH_ORDER";
    class PhotoUploadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {


                UserEntity userEntity = (UserEntity) intent.getSerializableExtra(Constant.KEY_DATA);

                int code = userEntity.getCode();

                if (code == 0) {
                    uploadWork();
                    //上传成功后退出
                } else if (code == Constant.STATUS_NO_NET) {
                    WaitingDialogControll.dismissWaitingDialog();
                    Toast.makeText(mContext, "请检查网络", Toast.LENGTH_SHORT).show();
                } else {
                    WaitingDialogControll.dismissWaitingDialog();
                    Toast.makeText(mContext, "上传失败", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    class WorkUploadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                int status = intent.getIntExtra(Constant.KEY_DATA,-1);
                WaitingDialogControll.dismissWaitingDialog();
                if(status == Constant.STATUS_OK){
//                    if(ToastUtil.isFastShow()){
                        Toast.makeText(WorkHomeOrderAddActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                        getApplicationContext().sendBroadcast(new Intent(WorkOrderListFragment.WORK_ORDER_REFRESH));
//                        new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrder.getWoId(),Constant.WORK_ORDER_HISTORY_GET,mWorkOrder.getWorkEqnos(), WorkOrderListFragment.WORK_ORDER_REFRESH);
                        finish();
//                    }
                }else {
//                    if(ToastUtil.isFastShow()){
                        Toast.makeText(WorkHomeOrderAddActivity.this, "操作失败,请重新操作", Toast.LENGTH_SHORT).show();
//                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Uri saveBitmap(Bitmap bitmap,String name) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(),"jiepiaisi");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = name + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return Uri.fromFile(file);
    }
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();

    }


    private String area = "";
    private String area2 = "";
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        //mCurAMapLocation = exchangeLocation(aMapLocation);
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                area = aMapLocation.getAddress();
                if(area.length() > 18){
                    String temp = area;
                    area = temp.substring(0,18);
                    area2 = temp.substring(18,temp.length());
                }
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }



    }




}
